Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
what is the explanation of this "(x > 0) - (x < 0) || +x;" with JavaScript

Can we use a minus operator as a Comparison Operator ?

I couldn't find like a this situtation.

function sign(x) {
    return (x > 0) - (x < 0) || +x;
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It will not act as a comparisons operator. It will act as a math operator. To this work, JavaScript converts the boolean resulting from the x > 0 and x < 0 to zero or one, then do the subtraction.

This is a weird code, but valid.

about 4 years ago · Juan Pablo Isaza Report

0

There are two steps to describe here.

Compute sign (+1, 0 or -1)

As already noted in Elia Soares's answer, JavaScript implicitly converts boolean expression to numbers when doing a subtraction. true will be converted to 1, and false to 0.

console.log(+true);
console.log(+false);

let x = 20;
console.log(+(x > 0));
console.log(+(x < 0));

then, doing (x > 0) - (x < 0) means:

  • If x is positive, we get 1 - 0, which gives 1.

  • If x is negative, we get 0 - 1, which gives -1.

  • If x is zero, we get 0 - 0, which gives 0.

This looks already good to create a sign(x) function as usually expected.

sign math function graph

Handle undefined

However, also consider undefined in this formula: any comparisons will give false, and so the above subtraction will give zero.

That's a bit dangerous, could be that you forgot to assign a value to the variable, which is a common bug when you write code.

That's why the || +x was added.

|| in javascript means:

Evaluate the left side. If it's truthy, return the left side. Otherwise, return the right side.

+1, and -1 are truthy, and 0 is falsy, so the full expression (x > 0) - (x < 0) || +x will evaluate to +x if and only if the subtraction gives zero.

If x is zero, this will still give +0 which is 0.

If x is null, this will give +null which is 0.

If x is undefined, this will give +undefined which is NaN.

Getting a NaN in your calculation will quickly cause all your subsequent results to be NaN, warning you that there was something undefined that you probably forgot.

Note that the +x still evaluate to 0 if x is null er empty string '', so this code won't change the (mayybe unexpected) result zero for those special cases.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!